package com.server.store.data;

import java.util.ArrayList;
import java.util.List;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;
import com.shared.model.Quittance;
import com.shared.model.etat.EtatQuittance;
import com.shared.model.etat.EtatQuittanceMiseEnDemeure;
import com.shared.model.etat.EtatQuittanceNonReglee;
import com.shared.model.etat.EtatQuittanceReglee;
import com.shared.utilitaire.Date;
/**
 * DAO de gestion des {@link Quittance}
 * @author queyroi
 *
 */
public class QuittanceManager extends DataManager<Quittance>{

	static{
		ObjectifyService.register(Date.class);
		ObjectifyService.register(Quittance.class);		
		ObjectifyService.register(EtatQuittance.class);	
		ObjectifyService.register(EtatQuittanceReglee.class);
		ObjectifyService.register(EtatQuittanceNonReglee.class);
		ObjectifyService.register(EtatQuittanceMiseEnDemeure.class);	
	}
	
	@Override
	public void delete(Quittance obj) {
		Objectify ofy2 = ObjectifyService.begin(); 	
		Objectify ofy = ObjectifyService.beginTransaction(); 
		try{
			ofy2.delete(obj.getEtatQuittance());			
			ofy.delete(obj);
			ofy.getTxn().commit();
		}catch(Exception e){
			e.printStackTrace();
			if (ofy.getTxn().isActive())
		        ofy.getTxn().rollback();
		}
		
	}
	
	
	
	
	@Override
	public List<Quittance> getList() {
		List<Quittance> listReturn = new ArrayList<Quittance>();
		Objectify ofy = ObjectifyService.begin();
		Query<Quittance> query = ofy.query(Quittance.class);
		for(Quittance a : query){
			listReturn.add(a);
		}
		return listReturn;
	}
	
	public EtatQuittance getEtatQuittance(Key<EtatQuittance> key) throws EntityNotFoundException{				
		Objectify ofy = ObjectifyService.begin();		
		return ofy.get(key);		
	}
	
	public Quittance getQuittance(Long key) throws EntityNotFoundException{
		Objectify ofy = ObjectifyService.begin();
		Quittance q = ofy.get(Quittance.class, key);
		return q;
	}

	public void setEtatQuittance(EtatQuittance etat,Quittance q){
		Objectify ofy = ObjectifyService.begin(); 		
		Objectify ofy2 = ObjectifyService.beginTransaction();
		try{						
			Key<EtatQuittance> key = ofy2.put(etat);			
			if(q.getEtatQuittance()!=null) ofy.delete(q.getEtatQuittance());
			System.out.println(key);
			q.setEtatQuittance(key);
			ofy2.getTxn().commit();
		}catch(Exception e){
			e.printStackTrace();
			if (ofy2.getTxn().isActive())
				ofy2.getTxn().rollback();
		}	
	} 
	
	public void validate(Quittance q) throws EntityNotFoundException{
		getEtatQuittance(q.getEtatQuittance()).valider(q);
	}
	
	public void validate(Long id) throws EntityNotFoundException{
		Quittance q = getQuittance(id);
		getEtatQuittance(q.getEtatQuittance()).valider(q);
	}

}
